package com.example.rpcprovider;

import com.example.rpc_core.RpcApplication;
import com.example.rpc_core.config.RegistryConfig;
import com.example.rpc_core.config.RpcConfig;
import com.example.rpc_core.model.ServiceMetaInfo;
import com.example.rpc_core.registry.LocalRegistry;
import com.example.rpc_core.registry.Registry;
import com.example.rpc_core.registry.RegistryFactory;
import com.example.rpc_core.server.VertxHttpServer;
import com.example.rpc_core.server.tcp.VertxTcpServer;
import com.example.rpccommon.service.UserService;

public class RpcProviderExampleApplication {

    public static void main(String[] args) {

        // RPC框架初始化
        RpcApplication.init();

//        // 注册服务
//        LocalRegistry.register(UserService.class.getName(), UserServiceImpl.class);

        // 注册服务
        String serviceName = UserService.class.getName();
        LocalRegistry.register(serviceName, UserServiceImpl.class);

        // 注册服务到注册中心
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
        serviceMetaInfo.setServiceName(serviceName);
        serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
        serviceMetaInfo.setServicePort(rpcConfig.getServerPort());

        // 注册多个服务到同一个注册中心 以测试负载均衡
        /*ServiceMetaInfo serviceMetaInfo2 = new ServiceMetaInfo();
        serviceMetaInfo2.setServiceName(serviceName);
        serviceMetaInfo2.setServiceHost(rpcConfig.getServerHost());
        serviceMetaInfo2.setServicePort(8088);

        ServiceMetaInfo serviceMetaInfo3 = new ServiceMetaInfo();
        serviceMetaInfo3.setServiceName(serviceName);
        serviceMetaInfo3.setServiceHost(rpcConfig.getServerHost());
        serviceMetaInfo3.setServicePort(8089);*/
        try {
            registry.register(serviceMetaInfo);
            /*registry.register(serviceMetaInfo2);
            registry.register(serviceMetaInfo3);*/
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 启动web服务 这里启动的是HTTP服务
//        VertxHttpServer httpServer = new VertxHttpServer();
//        httpServer.doStart(RpcApplication.getRpcConfig().getServerPort());

        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(RpcApplication.getRpcConfig().getServerPort());
    }
}
